package com.bootcamp.mall.filter;

import com.bootcamp.mall.model.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(value = "/api/admin/*")
public class AdminFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 从context中获取
        String origin = (String) req.getServletContext().getAttribute("origin");

        resp.setHeader("Access-Control-Allow-Origin", origin);
        resp.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
        resp.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setContentType("text/html;charset=UTF-8");

        // 记录当前method及sessionid
        System.out.println("method:   "+req.getMethod() + "\nsession:  "+req.getSession());
        // 当前请求如果使 OPTIONS ，放行
        if ("OPTIONS".equals(req.getMethod())) {
            chain.doFilter(req, resp);
            return;
        }
        // 判断当前uri是否为login,如果是则销毁当前session，放行
        String op = req.getRequestURI().replace(req.getContextPath() + "/api/admin/", "");
        if ("admin/login".equals(op)) {
            req.getSession().invalidate();
            chain.doFilter(req, resp);
            return;
        }
        // 获取session取出id
        Integer adminId = (Integer) req.getSession().getAttribute("adminId");
        // 如果存在，则直接放行
        if (adminId != null) {
            chain.doFilter(req, resp);
            return;
        }
        // 如果为null则说明非法访问，需要拦截
        resp.getWriter().println(new Gson().toJson(Result.error("当前接口仅允许登陆后访问！")));
    }
}
